package com.guigu.yh.springcloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 我日志网关过滤器  - 网关全局过滤器
 *
 * @author 张颖辉（zyh）
 * @version 1.0.0
 * @date 2022/10/29
 */
@Component
@Slf4j
public class MyLogGateWayGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("*********************** come in MyLogGateWayGlobalFilter: " + LocalDateTime.now());
        /* 过滤器逻辑：请求参数必须包含uname参数，否则拒绝接收请求 */
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if (uname == null) {
            log.warn("******** 用户名为空，非法用户，o(╥﹏╥)o");
            final ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 加载当前过滤器的顺序，越小越优先
     *
     * @return int
     * @author 张颖辉（zyh）
     * @date 2022/10/29
     * @version 1.0.0
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
